<template>
<div>
  <el-dialog
    :title="title"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="method==='view'"
             label-width="120px">
      <el-row  :gutter="15">
        <el-col :span="12" v-if="method !== 'add'">
            <el-form-item label="工单编号" prop="orderNo"
                :rules="[
                 ]">
              <el-input v-model="inputForm.orderNo" placeholder="请填写工单编号" :disabled="true"></el-input>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="工单来源" prop="source"
                :rules="[
                 ]">
                <el-select v-model="inputForm.source" placeholder="请选择" disabled style="width: 100%;">
                          <el-option
                            v-for="item in $dictUtils.getDictList('work_order_source')"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                          </el-option>
                      </el-select>
           </el-form-item>
        </el-col>

        <el-col :span="12">
            <el-form-item label="分类" prop="category"
                :rules="[
                 ]">
                <el-select v-model="inputForm.category" placeholder="请选择"  style="width: 100%;">
                          <el-option
                            v-for="item in $dictUtils.getDictList('work_order_category')"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                          </el-option>
                      </el-select>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="设备分类" prop="categoryId"
                :rules="[
                 ]">
                <el-select v-model="inputForm.categoryId" placeholder="请选择设备分类" style="width: 100%;" @change="loadDeviceList">
                    <el-option
                      v-for="item in categoryList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                </el-select>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="报修设备" prop="deviceId"
                :rules="[
                 ]">
                <el-select v-model="inputForm.deviceId" multiple placeholder="请选择报修设备" style="width: 100%;">
                    <el-option
                      v-for="item in deviceList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                </el-select>
           </el-form-item>
        </el-col>

        <el-col :span="12">
            <el-form-item label="工单状态" prop="status"
                :rules="[
                 ]">
                <el-select v-model="inputForm.status" placeholder="请选择"  style="width: 100%;">
                          <el-option
                            v-for="item in $dictUtils.getDictList('work_order_status')"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                          </el-option>
                      </el-select>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="优先级" prop="priority"
                :rules="[
                 ]">
                <el-select v-model="inputForm.priority" placeholder="请选择"  style="width: 100%;">
                          <el-option
                            v-for="item in $dictUtils.getDictList('work_order_priority')"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                          </el-option>
                      </el-select>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="维修员" prop="assignedTo"
                :rules="[
                 ]">
              <el-input v-model="inputForm.assignedTo" placeholder="请填写分配的维修员"     ></el-input>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="分配时间" prop="assignedAt"
                :rules="[
                 ]">
                <el-date-picker
                      style="width: 100%;"
                      v-model="inputForm.assignedAt"
                      type="datetime"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      placeholder="选择日期时间">
                    </el-date-picker>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="预计完成" prop="deadline"
                :rules="[
                 ]">
                <el-date-picker
                      style="width: 100%;"
                      v-model="inputForm.deadline"
                      type="datetime"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      placeholder="选择日期时间">
                    </el-date-picker>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="实际完成" prop="finishedAt"
                :rules="[
                 ]">
                <el-date-picker
                      style="width: 100%;"
                      v-model="inputForm.finishedAt"
                      type="datetime"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      placeholder="选择日期时间">
                    </el-date-picker>
           </el-form-item>
        </el-col>
        <el-col :span="24">
            <el-form-item label="故障描述" prop="faultDesc"
                :rules="[
                 ]">
              <el-input v-model="inputForm.faultDesc" type="textarea" :rows="4" placeholder="请填写故障描述"></el-input>
           </el-form-item>
        </el-col>
        </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">关闭</el-button>
      <el-button type="primary" v-if="method != 'view'" @click="doSubmit()" v-noMoreClick>确定</el-button>
    </span>
  </el-dialog>
</div>
</template>

<script>
  export default {
    data () {
      return {
        title: '',
        method: '',
        visible: false,
        loading: false,
        categoryList: [], // 设备分类列表
        deviceList: [], // 设备列表
        inputForm: {
          id: '',
          orderNo: '',
          source: '',
          requestId: '',
          category: '',
          categoryId: '', // 设备分类ID
          deviceId: [],
          faultDesc: '',
          status: '',
          priority: '',
          assignedTo: '',
          assignedAt: '',
          deadline: '',
          finishedAt: ''
        }
      }
    },
    components: {
    },
    methods: {
      init (method, id) {
        this.method = method
        this.inputForm.id = id
        if (method === 'add') {
          this.title = `新建工单`
          // 设置工单来源默认为"报修"
          this.inputForm.source = 'REPAIR_REQUEST'
          // 设置工单状态默认为待处理
          this.inputForm.status = 'PENDING'
          // 设置优先级默认为低
          this.inputForm.priority = 'LOW'
          // 设置分配时间默认为当前时间
          this.inputForm.assignedAt = this.formatDateTime(new Date())
          // 设置预计完成时间默认为次日结束时间
          this.inputForm.deadline = this.formatDateTime(this.getEndOfDay(1))
          // 设置实际完成时间默认也为次日结束时间
          this.inputForm.finishedAt = this.formatDateTime(this.getEndOfDay(1))
        } else if (method === 'edit') {
          this.title = '修改工单'
        } else if (method === 'view') {
          this.title = '查看工单'
        }
        this.visible = true
        this.loading = false

        // 加载设备分类列表
        this.loadCategoryList()

        this.$nextTick(() => {
          this.$refs.inputForm.resetFields()
          if (method === 'edit' || method === 'view') { // 修改或者查看
            this.loading = true
            this.$http({
              url: `/workorder/workOrder/queryById?id=${this.inputForm.id}`,
              method: 'get'
            }).then(({data}) => {
              this.inputForm = this.recover(this.inputForm, data.workOrder)
              // 如果有设备分类ID，加载对应的设备列表
              if (this.inputForm.categoryId) {
                this.loadDeviceList(this.inputForm.categoryId).then(() => {
                  // 反显多选设备（后端返回逗号分隔字符串时）
                  if (this.inputForm.deviceId) {
                    this.inputForm.deviceId = typeof this.inputForm.deviceId === 'string'
                      ? this.inputForm.deviceId.split(',').filter(Boolean)
                      : Array.isArray(this.inputForm.deviceId)
                        ? this.inputForm.deviceId
                        : []
                  } else {
                    this.inputForm.deviceId = []
                  }
                  this.loading = false
                }).catch(() => {
                  this.loading = false
                })
              }
              else {
                this.loading = false
              }
            })
          }
        })
      },
      // 表单提交
      doSubmit () {
        this.$refs['inputForm'].validate((valid) => {
          if (valid) {
            // 将设备ID数组转换为逗号分隔的字符串提交
            const submitData = {
              ...this.inputForm,
              deviceId: Array.isArray(this.inputForm.deviceId)
                ? this.inputForm.deviceId.filter(Boolean).join(',')
                : typeof this.inputForm.deviceId === 'string'
                  ? this.inputForm.deviceId
                  : ''
            }
            this.loading = true
            this.$http({
              url: `/workorder/workOrder/save`,
              method: 'post',
              data: submitData
            }).then(({data}) => {
              if (data && data.success) {
                this.visible = false
                this.$message.success(data.msg)
                this.$emit('refreshDataList')
              }
              this.loading = false
            })
          }
        })
      },
      // 加载设备分类列表
      loadCategoryList () {
        this.$http({
          url: '/device/equipmentCategory/list',
          method: 'get'
        }).then(({data}) => {
          if (data && data.success) {
            // 根据实际响应结构调整数据处理逻辑
            // 响应数据在 data.page.list 中
            const list = data.page && data.page.list ? data.page.list : []
            this.categoryList = list.map(item => {
              return {
                id: item.id || '',
                name: item.name || ''
              }
            })
          } else {
            // 如果接口调用失败，显示错误信息
            this.$message.error(data.msg || '加载设备分类失败')
          }
        }).catch(error => {
          console.error('加载设备分类出错:', error)
          this.$message.error('加载设备分类失败，请检查网络连接')
        })
      },

      // 格式化日期时间为 yyyy-MM-dd HH:mm:ss
      formatDateTime(date) {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      },
      // 获取指定天数后的结束时间 (23:59:59)，默认为当天
      getEndOfDay(daysToAdd = 0) {
        const date = new Date()
        date.setDate(date.getDate() + daysToAdd)
        date.setHours(23, 59, 59, 999)
        return date
      },
      // 根据分类ID加载设备列表
      loadDeviceList (categoryId) {
        return new Promise((resolve) => {
          if (!categoryId) {
            this.deviceList = []
            this.inputForm.deviceId = []
            resolve()
            return
          }

          this.$http({
            url: '/device/equipment/list',
            method: 'get',
            params: {
              categoryId: categoryId
            }
          }).then(({data}) => {
            if (data && data.success) {
              // 根据实际响应结构调整数据处理逻辑
              // 响应数据在 data.page.list 中
              const list = data.page && data.page.list ? data.page.list : []
              this.deviceList = list.map(item => {
                return {
                  id: item.id || '',
                  name: item.name || ''
                }
              })
              // 过滤掉不在新设备列表中的已选项
              if (Array.isArray(this.inputForm.deviceId)) {
                const allowedIds = new Set(this.deviceList.map(i => i.id))
                this.inputForm.deviceId = this.inputForm.deviceId.filter(id => allowedIds.has(id))
              }
            } else {
              // 如果接口调用失败，显示错误信息
              this.$message.error(data.msg || '加载设备列表失败')
              this.deviceList = []
            }
            resolve()
          }).catch(error => {
            console.error('加载设备列表出错:', error)
            this.$message.error('加载设备列表失败，请检查网络连接')
            this.deviceList = []
            resolve()
          })
        })
      }
    }
  }
</script>
